


package jnpf.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import jnpf.annotation.JnpfField;
import jnpf.base.ActionResult;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.base.UserInfo;
import jnpf.base.vo.DownloadVO;
import jnpf.config.ConfigValueUtil;
import jnpf.exception.DataException;
import jnpf.onlinedev.model.ExcelImFieldModel;
import jnpf.onlinedev.model.OnlineImport.ExcelImportModel;
import jnpf.onlinedev.model.OnlineImport.VisualImportModel;
import jnpf.permission.entity.UserEntity;
import jnpf.service.MzProjectcontentService;
import jnpf.util.treeutil.ListToTreeUtil;
import jnpf.util.treeutil.SumTree;
import jnpf.util.treeutil.TreeDotUtils;
import org.springframework.transaction.annotation.Transactional;
import jnpf.base.entity.ProvinceEntity;
import jnpf.model.mzcompilationtype.*;
import jnpf.model.mzcompilationtype.MzCompilationtypePagination;
import jnpf.entity.*;
import jnpf.util.*;
import jnpf.base.util.*;
import jnpf.base.vo.ListVO;
import jnpf.util.context.SpringContext;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.Cleanup;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import jnpf.entity.MzCompilationtypeEntity;
import jnpf.service.MzCompilationtypeService;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import jnpf.util.GeneraterSwapUtil;

import java.util.stream.Collectors;
import java.util.*;

import cn.xuyanwu.spring.file.storage.FileInfo;


/**
 * mzCompilationtype
 *
 * @版本： V3.2.0
 * @版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2024-01-15
 */
@Slf4j
@RestController
@Tag(name = "mzCompilationtype", description = "example")
@RequestMapping("/api/example/MzCompilationtype")
public class MzCompilationtypeController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;


    @Autowired
    private UserProvider userProvider;

    @Autowired
    private MzProjectcontentService mzProjectcontentService;
    @Autowired
    private MzCompilationtypeService mzCompilationtypeService;


    /**
     * 列表
     *
     * @param mzCompilationtypePagination
     * @return
     */
    @Operation(summary = "获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody MzCompilationtypePagination mzCompilationtypePagination) throws IOException {
        //树形判断是否有参数，有参数不造树
        if (mzCompilationtypePagination.getTypename() != null && mzCompilationtypePagination.getTypename() != "") {
            mzCompilationtypePagination.setHasParam(true);
        }
        if (mzCompilationtypePagination.getTypecode() != null && mzCompilationtypePagination.getTypecode() != "") {
            mzCompilationtypePagination.setHasParam(true);
        }
        if (StringUtil.isNotEmpty(mzCompilationtypePagination.getSuperQueryJson())) {
            mzCompilationtypePagination.setHasParam(true);
        }
        List<MzCompilationtypeEntity> list = mzCompilationtypeService.getList(mzCompilationtypePagination);
        //处理id字段转名称，若无需转或者为空可删除

        List<MzCompilationtypeListVO> listVO = JsonUtil.getJsonToList(list, MzCompilationtypeListVO.class);
        for (MzCompilationtypeListVO mzCompilationtypeVO : listVO) {
            ActionResult info = info(mzCompilationtypeVO.getId());
            Map<String, Object> dataMap = JsonUtil.entityToMap(info.getData());
            mzCompilationtypeVO.setTypename_name(mzCompilationtypeVO.getTypename());

            mzCompilationtypeVO.setTypecode_name(mzCompilationtypeVO.getTypecode());
            if(StringUtil.isNotEmpty( mzCompilationtypeVO.getParentid())){
                MzCompilationtypeEntity compilationtype = mzCompilationtypeService.getInfo(mzCompilationtypeVO.getParentid());
                if(StringUtil.isNotNull(compilationtype)){
                    mzCompilationtypeVO.setParentid_name(compilationtype.getTypename());
                }
               /* mzCompilationtypeVO.setParentid_name(generaterSwapUtil.getDynName("503326883694248005", "fullName", "id",
                        "children", mzCompilationtypeVO.getParentid(), false, true,
                        "[{\"dataType\":\"varchar\",\"defaultValue\":\"\",\"field\":\"typename\",\"fieldName\":\"" +
                                "\",\"id\":\"vExf1v1\",\"jnpfKey\":null,\"relationField\":\"\"," +
                                "\"required\":\"0\"},{\"dataType\":\"varchar\",\"defaultValue\":\"\",\"field\":\"typecode\"," +
                                "\"fieldName\":\"\",\"id\":\"o55g1v1\",\"jnpfKey\":null,\"relationField\":\"\",\"required\":\"0\"}]", -1, dataMap));*/
            }
            mzCompilationtypeVO.setEnabledmark_name(generaterSwapUtil.switchSelectValue(mzCompilationtypeVO.getEnabledmark(), "是", "否"));

            mzCompilationtypeVO.setIsshow_name(generaterSwapUtil.switchSelectValue(mzCompilationtypeVO.getIsshow(), "是", "否"));

            mzCompilationtypeVO.setSort_name(mzCompilationtypeVO.getSortcode().toString());

            mzCompilationtypeVO.setDescription_name(mzCompilationtypeVO.getDescription());

            //子表数据转换
        }

        if (!mzCompilationtypePagination.isHasParam()) {
            for (int i = 0; i < listVO.size(); i++) {
                MzCompilationtypeListVO item = listVO.get(i);
                if (!StringUtil.isEmpty(item.getParentid())) {
                    if (addChild(item, listVO) && listVO.size() > 0) {
                        listVO.remove(item);
                        i--;
                    }
                }
            }
        }
        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        return ActionResult.success(vo);

    }

    //树形递归
    private static boolean addChild(MzCompilationtypeListVO node, List<MzCompilationtypeListVO> list) {
        for (int i = 0; i < list.size(); i++) {
            MzCompilationtypeListVO n = list.get(i);
            if (n.getId().equals(node.getParentid())) {
                if (n.getChildren() == null) {
                    n.setChildren(new ArrayList<>());
                }
                List<MzCompilationtypeListVO> children = n.getChildren();
                children.add(node);
                n.setChildren(children);
                return true;
            }
            if (n.getChildren() != null) {
                List<MzCompilationtypeListVO> children = n.getChildren();
                if (addChild(node, children)) {
                    return true;
                }
            }

        }
        return false;
    }

    /**
     * 获取树形列表
     *
     * @param mzCompilationtypePagination 分页参数
     * @return ignore
     */
    @Operation(summary = "获取树形列表")
    @PostMapping("/getTreeList")
    public ActionResult getTreeList(@RequestBody MzCompilationtypePagination mzCompilationtypePagination) {
        List<MzCompilationtypeEntity> data = mzCompilationtypeService.getTreeList(mzCompilationtypePagination);
        List<MzCompilationtypeEntity> dataAll = data;

        List<MzCompilationtypeEntity> treeData = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(data, dataAll), MzCompilationtypeEntity.class);
        List<CompilationtyepModel> voListVO = JsonUtil.getJsonToList(treeData, CompilationtyepModel.class);
        List<SumTree<CompilationtyepModel>> sumTrees = TreeDotUtils.convertListToTreeDot(voListVO);
        List<CompilationtypeListVO> list = JsonUtil.getJsonToList(sumTrees, CompilationtypeListVO.class);
        ListVO<CompilationtypeListVO> treeVo = new ListVO<>();
        treeVo.setList(list);
        return ActionResult.success(treeVo);
    }

    /**
     * 创建
     *
     * @param mzCompilationtypeForm
     * @return
     */
    @PostMapping
    @Transactional
    @Operation(summary = "创建")
    public ActionResult create(@RequestBody @Valid MzCompilationtypeForm mzCompilationtypeForm) throws DataException {
        String b = mzCompilationtypeService.checkForm(mzCompilationtypeForm, 0);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b + "不能重复");
        }
        String mainId = RandomUtil.uuId();

        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        GeneraterSwapUtil.swapDatetime(mzCompilationtypeForm);
        MzCompilationtypeEntity entity = JsonUtil.getJsonToBean(mzCompilationtypeForm, MzCompilationtypeEntity.class);
        entity.setId(mainId);
        mzCompilationtypeService.save(entity);


        return ActionResult.success("创建成功");
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @Operation(summary = "信息")
    @GetMapping("/{id}")
    public ActionResult<MzCompilationtypeInfoVO> info(@PathVariable("id") String id) {
        MzCompilationtypeEntity entity = mzCompilationtypeService.getInfo(id);
        MzCompilationtypeInfoVO vo = JsonUtil.getJsonToBean(entity, MzCompilationtypeInfoVO.class);

        //子表
        //副表
        return ActionResult.success(vo);
    }

    /**
     * 表单信息(详情页)
     *
     * @param id
     * @return
     */
    @Operation(summary = "表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<MzCompilationtypeInfoVO> detailInfo(@PathVariable("id") String id) {
        ActionResult info = info(id);
        Map<String, Object> dataMap = JsonUtil.entityToMap(info.getData());
        MzCompilationtypeEntity entity = mzCompilationtypeService.getInfo(id);
        MzCompilationtypeInfoVO vo = JsonUtil.getJsonToBean(entity, MzCompilationtypeInfoVO.class);

        //子表数据转换

        //附表数据转换

//添加到详情表单对象中
        vo.setTypename(vo.getTypename());

        vo.setTypecode(vo.getTypecode());

        vo.setParentid(generaterSwapUtil.getDynName("503326883694248005", "fullName", "id", "children", vo.getParentid(), false, true, "[{\"dataType\":\"varchar\",\"defaultValue\":\"\",\"field\":\"typename\",\"fieldName\":\"\",\"id\":\"vExf1v1\",\"jnpfKey\":null,\"relationField\":\"\",\"required\":\"0\"},{\"dataType\":\"varchar\",\"defaultValue\":\"\",\"field\":\"typecode\",\"fieldName\":\"\",\"id\":\"o55g1v1\",\"jnpfKey\":null,\"relationField\":\"\",\"required\":\"0\"}]", -1, dataMap));

        vo.setEnabledmark(generaterSwapUtil.switchSelectValue(vo.getEnabledmark(), "1", "2"));

        vo.setIsshow(generaterSwapUtil.switchSelectValue(vo.getIsshow(), "1", "2"));

        vo.setSort_name(generaterSwapUtil.getDecimalStr(vo.getSort()));

        vo.setDescription(vo.getDescription());


        return ActionResult.success(vo);
    }


    /**
     * 更新
     *
     * @param id
     * @param mzCompilationtypeForm
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    @Operation(summary = "更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid MzCompilationtypeForm mzCompilationtypeForm) throws DataException {
        String b = mzCompilationtypeService.checkForm(mzCompilationtypeForm, 1);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b + "不能重复");
        }
        UserInfo userInfo = userProvider.get();
        MzCompilationtypeEntity entity = mzCompilationtypeService.getInfo(id);
        if (entity != null) {
            GeneraterSwapUtil.swapDatetime(mzCompilationtypeForm);
            MzCompilationtypeEntity subentity = JsonUtil.getJsonToBean(mzCompilationtypeForm, MzCompilationtypeEntity.class);
            boolean b1 = mzCompilationtypeService.updateById(subentity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }

    /**
     * 更新是否启用
     *
     * @param mzCompilationtypeForm
     * @param mzCompilationtypeForm
     * @return
     */
    @PostMapping("/enabledmark")
    @Transactional
    @Operation(summary = "更新")
    public ActionResult enabledmark(@RequestBody @Valid MzCompilationtypeForm mzCompilationtypeForm) throws DataException {
        if (!StringUtil.isNotEmpty(mzCompilationtypeForm.getId())||StringUtil.isEmpty(mzCompilationtypeForm.getEnabledmark())) {
            return ActionResult.fail("主键或是否启用不能为空");
        }
        UserInfo userInfo = userProvider.get();
        MzCompilationtypeEntity entity = mzCompilationtypeService.getInfo(mzCompilationtypeForm.getId());
        if (entity != null) {
            GeneraterSwapUtil.swapDatetime(mzCompilationtypeForm);
            entity.setEnabledMark(Integer.parseInt(mzCompilationtypeForm.getEnabledmark()));
            boolean b1 = mzCompilationtypeService.updateById(entity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        MzCompilationtypeEntity entity = mzCompilationtypeService.getInfo(id);
        if (entity != null) {
            //如果在采编内容中有关联则不能删除
            List<MzProjectcontentEntity> projectcontentlist = mzProjectcontentService.getMzProjectcontentByTypeId(id);
            if(projectcontentlist.size()>0){
                return ActionResult.success("请删除采编内容关联数据后，再执行此操作");
            }
            //递归删除
            List<MzCompilationtypeEntity> list = mzCompilationtypeService.getList(new MzCompilationtypePagination());
            for (MzCompilationtypeEntity item : list) {
                if (StringUtil.isNotEmpty(item.getParentId()) && entity.getId().equals(item.getParentId())) {
                    List<MzProjectcontentEntity> projectcontentlist1 = mzProjectcontentService.getMzProjectcontentByTypeId(item.getId());
                    if(projectcontentlist1.size()>0){
                        return ActionResult.success("请删除采编内容关联数据后，再执行此操作");
                    }
                    this.delete(item.getId());
                }
            }
            mzCompilationtypeService.delete(entity);
        }
        return ActionResult.success("删除成功");
    }


}
